<?php
require_once (dirname(__FILE__) . "/inc/session_auth.php");
// we don't have to update $_SESSION
session_write_close();
?>
<?php

require_once (dirname(__FILE__) . "/inc/response.php");
require_once (dirname(__FILE__) . "/inc/class/common/db/GenericDao.php");
?>
<?php

require_once (dirname(__FILE__) . "/inc/debug.php");
require_once (dirname(__FILE__) . "/inc/class/init.php");
?>
<?php

/* WidgetFramework Talk
 * Created: 200904 (TT Tsai)
 */
// load data from POST string
$widgetRequest = json_decode($HTTP_RAW_POST_DATA, true);
if($widgetRequest == null){
    // input format error
    make_error_response(WF_ERRCODE_INVALIDFORMAT, WF_ERRCODE_INVALIDFORMAT_MSG);
    exit();
}
// check act=
if(! isset($widgetRequest['act'])){
    // act is not specified
    make_error_response(WF_ERRCODE_NOACT, WF_ERRCODE_NOACT_MSG);
    exit();
}
// userid
if(! isset($_SESSION['uid'])){
    make_error_response(WF_ERRCODE_ERR, WF_ERRCODE_ERR_MSG . ": retrieving userid failed");
    exit();
}
$userid = $_SESSION['uid'];
// database object
$wfdbobj = new WFGenericDao($wfconf_dbconfig["table"]["users"]["name"], $wfconf_dbconfig["table"]["userdata"]["name"], $wfconf_dbconfig, $userid);
if($wfdbobj->isFailed()){
    make_error_response(WF_ERRCODE_DBINIT, WF_ERRCODE_DBINIT_MSG . ": " . $wfdbobj->getErrMessage());
    exit();
}
// check input
if(isset($widgetRequest['pid']) && (! is_numeric($widgetRequest['pid']))){
    make_error_response(WF_ERRCODE_INVALIDINPUT, WF_ERRCODE_INVALIDINPUT_MSG . ": [pid]");
    exit();
}
// check wid
if(isset($widgetRequest['wid']) && (! is_numeric($widgetRequest['wid']))){
    make_error_response(WF_ERRCODE_INVALIDINPUT, WF_ERRCODE_INVALIDINPUT_MSG . ": [wid]");
    exit();
}
switch($widgetRequest['act']){
    case "getUdataAll":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        // load user
        $uinfolist = $wfdbobj->get_users();
        if($wfdbobj->isFailed()){
            mydebug_log("[WFTALK](act=getUdataAll): " . $wfdbobj->getErrMessage());
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=getUdataAll): " . $wfdbobj->getErrMessage());
            return false;
        }
        // no exists
        if(! isset($uinfolist[0])){
            mydebug_log("[WFTALK]: get_users - no user");
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=getUdataAll): " . $wfdbobj->getErrMessage());
            return false;
        }
        // get userinfo
        $userinfo = $uinfolist[0];
        $udataAll = array();
        $intContainerId = $widgetRequest['cid'];
        $intUserId = $_SESSION['uid'];
        $arrsUdata = WF::getControllerFactory()->getDbController()->getArrsUserdataByCondition($intContainerId, $intUserId);
        
        $intContainerId = $widgetRequest['cid'];
        $jsonPdata = $userinfo['pdata'];
        $arrsPdata = WF::getControllerFactory()->getDbController()->getArrsPdataByContainerIdAndJsonPdata($intContainerId, $jsonPdata);
        
        $udataAll['udata'] = $arrsUdata;
        $udataAll['pdata'] = $arrsPdata;
        $udataAll['theme'] = $userinfo['theme'];
        $udataAll['lang'] = $userinfo['lang'];
        make_successful_response(null, $udataAll);
        break;
    case "getWcomponentNameAll":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        $arrsWcomponentCategory = WF::getControllerFactory()->getDbController()->getArrsWcomponentCategory();
        $assocsCategory = array();
        if(is_array($arrsWcomponentCategory) && $arrsWcomponentCategory){
            foreach($arrsWcomponentCategory as $arrWcomponentCategory){
                $assocsCategory[] = array(
                    'category_product_id' => $arrWcomponentCategory['category_product_id'],
                    'category_name' => $arrWcomponentCategory['category_name']
                );
            }
        }
        make_successful_response(null, $assocsCategory);
        break;
    case "getWcomponentParamByWcomponentName":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        $strWcomponentName = $widgetRequest['wcomponent_name'];
        $strWcomponentParam = WF::getControllerFactory()->getDbController()->getWcomponentParamByWcomponentName($strWcomponentName);
        make_successful_response(null, array('wcomponent_param'=>$strWcomponentParam));
        break;
	case "getWcomponentNameAllWithCustomFields" :
        mydebug_log( "[WFTALK] act:" . $widgetRequest ['act'] );
        $arrsWcomponentCategory = WF::getControllerFactory()->getDbController()->getArrsWcomponentCategoryWithCustomizedFields();
        
        $categoryWithCustomFields = array ();
        
        /*
         * get every proxy's customized fields and store them to another array
         * in order to decrease data amount if two or more product ids use the same proxy
         */
        if(is_array( $arrsWcomponentCategory ) && $arrsWcomponentCategory){
            $colCustomFields = array ();
            
            foreach( $arrsWcomponentCategory as &$category ){
                if($category ['customFields'] != null){
                    $category_proxy = $category ['category_proxy'];
                    
                    // process password information due to prevent real value from beening transfered to browser
                    if(! isset( $colCustomFields [$category_proxy] )){
                        $customFields = json_decode( $category ['customFields'] ); // decode json(customFields) to obj
                        $isModify = false;
                        
                        foreach( $customFields as &$field ){ // field is stdClass
                            if($field->type == 'password' && $field->value != ''){
                                $field->value = '*****';
                                $isModify = true;
                            }
                        }
                        unset( $field );
                        
                        if($isModify){
                            $colCustomFields [$category_proxy] = json_encode( $customFields );
                        } else{
                            $colCustomFields [$category_proxy] = $category ['customFields'];
                        }
                    }
                }
                unset( $category ['customFields'] );
            }
            unset( $category );
            
            $categoryWithCustomFields [0] = $arrsWcomponentCategory;
            $categoryWithCustomFields [1] = $colCustomFields;
        }
        make_successful_response( null, $categoryWithCustomFields );
        break;    		
    case "getArrsWcomponentByCategoryProductId":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        $intCategoryProductId = $widgetRequest['category_product_id'];
        $arrsWcomponent = WF::getControllerFactory()->getDbController()->getArrsWcomponentByCategoryProductId($intCategoryProductId);
        make_successful_response(null, $arrsWcomponent);
        break;
    case "getPageNumberPlusOne":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        // load wdata from userdata
        $intUserId = $_SESSION['uid'];
        $intPageNumberPlusOne = WF::getControllerFactory()->getDbController()->getPageNumberPlusOneByUserId($intUserId);
        make_successful_response(null, array('page_number_plus_one'=>$intPageNumberPlusOne));
        break;
    case "getContainerIdByContainerName":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        $strContainerName = $widgetRequest['container_name'];
        $intContainerId = WF::getControllerFactory()->getDbController()->getContainerIdByContainerName($strContainerName);
        make_successful_response(null, array('container_id'=>$intContainerId));
        break;
    case "getWdataAll":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']);
        // load wdata from userdata
        $intContainerId = $widgetRequest['cid'];
        $intUserId = $_SESSION['uid'];
        $winfolist = WF::getControllerFactory()->getDbController()->getArrsUserdataByCondition($intContainerId, $intUserId);
        // prepare output
        $wdataAll = array();
        foreach($winfolist as $winfo){
            $winfo_output = array();
            $winfo_output['wid'] = $winfo['wid'];
            $winfo_output['pid'] = $winfo['pid'];
            
            $data = json_decode($winfo['data'], true);
            $dataArr = json_decode($data[0], true);
            if (isset($dataArr['wfUserData']) && isset($dataArr['wfMiscData'])) {
                $winfo_output['data'] = json_encode($dataArr['wfUserData']);
                $winfo_output['miscData'] = $dataArr['wfMiscData'];
            } else {
                $winfo_output['data'] = $data[0];
                $winfo_output['miscData'] = array();
            }
            
            $winfo_output['widget_key'] = $winfo['widget_key'];
            $winfo_output['param'] = json_decode($winfo['param'], true);
            $winfo_output['param'] = $winfo_output['param'][0];
            $wdataAll[] = $winfo_output;
        }
        make_successful_response(null, $wdataAll);
        break;
    case "module":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pid:" . $widgetRequest['pid'] . ", wid:" . $widgetRequest['wid'] . ", data:" . $widgetRequest['data']);
        // check input
        if((! isset($widgetRequest['pid'])) || (! isset($widgetRequest['wid']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // prepare update data
        $newinfo = array();
        $newinfo["pid"] = $widgetRequest["pid"];
        // data is an object (we treat "data" as an object)
        $newinfo["data"] = json_encode(array($widgetRequest["data"]));
        $wfdbobj->update_userdata($newinfo, $widgetRequest["wid"]);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=module): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_SAVED, null);
        break;
    case "moduledelete":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pid:" . $widgetRequest['pid'] . ", wid:" . $widgetRequest['wid']);
        // check input
        if((! isset($widgetRequest['pid'])) || (! isset($widgetRequest['wid']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        $wfdbobj->del_userdata($widgetRequest['pid'], $widgetRequest['wid']);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=moduledelete): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_DELETED, null);
        break;
    case "addWidgets":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act']. ", pid:". $widgetRequest['pid'] . ", udata:" . json_encode($widgetRequest['udata']) . ", wdata:" . json_encode($widgetRequest['wdata']) . ", updatedOriginalUdata:" . json_encode($widgetRequest['updatedOriginalUdata']));
        // check input
        if((! isset($widgetRequest['pid'])) || (! isset($widgetRequest['udata'])) || (! isset($widgetRequest['wdata']) || (! isset($widgetRequest['updatedOriginalUdata'])))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // udata -------------------
        // get current udata
        $original_udata = $wfdbobj->get_udata();
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=addWidgets(get udata)): " . $wfdbobj->getErrMessage());
            exit();
        }
        //update order of original data and add new data
        $merged_udata = array();
        foreach($original_udata as $o_udata){
            if($o_udata["page"] != $widgetRequest['pid']){
                $merged_udata[] = $o_udata;
            }
        }
        $merged_udata = array_merge($merged_udata, $widgetRequest['udata'], $widgetRequest['updatedOriginalUdata']);
        // update database
        $newinfo["udata"] = json_encode($merged_udata);
        $wfdbobj->update_users($newinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=addWidgets)(write udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        // wdata -------------------
        foreach($widgetRequest['wdata'] as $winfo){
            $wfdbobj->add_userdata($winfo);
            if($wfdbobj->isFailed()){
                make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=addWidgets)(insert wdata): " . $wfdbobj->getErrMessage());
                exit();
            }
        }
        make_successful_response(WF_OK_MODULE_ADDED, null);
        break;
    case "getModule":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pid:" . $widgetRequest['pid']);
        // check input
        if((! isset($widgetRequest['pid']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // get udata
        $udata = $wfdbobj->get_udata();
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=addWidgets)(get udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        $output_udata = array();
        foreach($udata as $uinfo){
            if($uinfo["page"] == $widgetRequest['pid']){
                $output_udata[] = $uinfo;
            }
        }
        make_successful_response(null, $output_udata);
        break;
    case "getWidgetdata":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", wid:" . $widgetRequest['wid']);
        // check input
        if((! isset($widgetRequest['wid']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // get widget data
        $cond = array();
        $cond["wid"] = $widgetRequest['wid'];
        $winfo = $wfdbobj->get_userdata($cond);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=getWidgetdata): " . $wfdbobj->getErrMessage());
            exit();
        }
        $originalobj = json_decode($winfo[0]["data"], true);
        make_successful_response(null, $originalobj[0]);
        break;
    /*
	case "getWidgetdataAll":
		mydebug_log("[WFTALK] act:".$widgetRequest['act']);
		// get all widget settings (an array)
		$winfolist = $wfdbobj->get_userdata(null);
		if( $wfdbobj->isFailed() ) {
			make_error_response( WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG."(act=getWidgetdataAll): ".$wfdbobj->getErrMessage());
			exit;
		}
		$winforesult = array();
		foreach( $winfolist as $winfo ) {
			$winfo_tmp = array();
			$winfo_tmp['wid'] = $winfo['wid'];
			$winfo_tmp['modname'] = $winfo['modname'];
			$winfo_tmp['data'] = json_decode($winfo['data'],true);
			$winfo_tmp['data'] = $winfo_tmp['data'][0];
			$winforesult[] = $winfo_tmp;
		}
		make_successful_response(null, $winforesult);
		break;
*/
    case "delTab":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pid:" . $widgetRequest['pid']);
        // check input
        if((! isset($widgetRequest['pid']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // delete data in userdata
        $wfdbobj->del_userdata($widgetRequest['pid'], 0);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=delTab): " . $wfdbobj->getErrMessage());
            exit();
        }
        // delete data in users
        // get current udata
        $udata = $wfdbobj->get_udata();
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=delTab)(get udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        $new_udata = array();
        foreach($udata as $uinfo){
            if($uinfo["page"] != $widgetRequest['pid']){
                $new_udata[] = $uinfo;
            }
        }
        // update back to db
        $tblinfo = array();
        $tblinfo["udata"] = json_encode($new_udata);
        $wfdbobj->update_users($tblinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=delTab)(update udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_TAB_REMOVED, null);
        break;
    case "udatanew":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pid:" . $widgetRequest['pid'] . ", udata:" . json_encode($widgetRequest['udata']) . ", wdata:" . json_encode($widgetRequest['wdata']));
        // check input
        if((! isset($widgetRequest['pid'])) || (! isset($widgetRequest['udata'])) || (! isset($widgetRequest['wdata']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // update to users
        $tblinfo = array();
        $tblinfo["udata"] = json_encode($widgetRequest['udata']);
        $wfdbobj->update_users($tblinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=udatanew)(update udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        // update to userdata
        foreach($widgetRequest['wdata'] as $winfo){
            $wfdbobj->adduserdata($winfo);
            if($wfdbobj->isFailed()){
                make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=udatanew)(update wdata): " . $wfdbobj->getErrMessage());
                exit();
            }
        }
        make_successful_response(WF_OK_MODULE_UDATA_SAVED, null);
        break;
    case "udata":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pid:" . $widgetRequest['pid'] . ", udata:" . json_encode($widgetRequest['udata']));
        // check input
        if((! isset($widgetRequest['pid'])) || (! isset($widgetRequest['udata']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // get current udata
        $udata = $wfdbobj->get_udata();
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=udata)(get udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        $new_udata = $widgetRequest['udata'];
        foreach($udata as $uinfo){
            if($uinfo["page"] != $widgetRequest['pid']){
                $new_udata[] = $uinfo;
            }
        }
        // update to users
        $tblinfo = array();
        $tblinfo["udata"] = json_encode($new_udata);
        $wfdbobj->update_users($tblinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=udata)(update udata): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_UDATA_SAVED, null);
        break;
    case "pdata":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", pdata:" . json_encode($widgetRequest['pdata']));
        // check input
        if((! isset($widgetRequest['pdata']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // update to users
        $intUserId = $_SESSION['uid'];
        $arrsPdata = WF::getControllerFactory()->getDbController()->getArrsPdataByUserId($intUserId);
        $arrsPdataSaveToDb = $arrsPdata;
        if(is_array($arrsPdata) && $arrsPdata){
            foreach($arrsPdata as $key => $arrPdata){
                if($widgetRequest['cid'] == $arrPdata['container_id']){
                    unset($arrsPdataSaveToDb[$key]);
                }
            }
        }
        $arrsPdataFromRequest = $widgetRequest['pdata'];
        if(is_array($arrsPdataFromRequest) && $arrsPdataFromRequest){
            foreach($arrsPdataFromRequest as $arrPdataFromRequest){
                $arrsPdataSaveToDb[] = $arrPdataFromRequest;
            }
            
        }
        $tblinfo = array();
        $arrPdataSaveToDb = (is_array($arrsPdataSaveToDb) && $arrsPdataSaveToDb) ? array_values($arrsPdataSaveToDb) : array();
        $tblinfo["pdata"] = json_encode($arrPdataSaveToDb);
        //$tblinfo["pdata"] = json_encode($widgetRequest['pdata']);
        
        $wfdbobj->update_users($tblinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=pdata): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_PDATA_SAVED, null);
        break;
    case "theme":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", theme:" . $widgetRequest['theme']);
        // check input
        if((! isset($widgetRequest['theme']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // update to users
        $tblinfo = array();
        $tblinfo["theme"] = $widgetRequest['theme'];
        $wfdbobj->update_users($tblinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=theme): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_THEME_SAVED, null);
        break;
    case "lang":
        mydebug_log("[WFTALK] act:" . $widgetRequest['act'] . ", lang:" . $widgetRequest['lang']);
        // check input
        if((! isset($widgetRequest['lang']))){
            make_error_response(WF_ERRCODE_LACKINPUT, WF_ERRCODE_LACKINPUT_MSG);
            exit();
        }
        // update to users
        $tblinfo = array();
        $tblinfo["lang"] = $widgetRequest['lang'];
        $wfdbobj->update_users($tblinfo);
        if($wfdbobj->isFailed()){
            make_error_response(WF_ERRCODE_DBERR, WF_ERRCODE_DBERR_MSG . "(act=lang): " . $wfdbobj->getErrMessage());
            exit();
        }
        make_successful_response(WF_OK_MODULE_LANG_SAVED, null);
        break;
    default:
        make_error_response(WF_ERRCODE_ACTERR, WF_ERRCODE_ACTERR_MSG);
        exit();
}
?>
